import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { message } from 'ant-design-vue'
import JSONBig from 'json-bigint'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000, // request timeout

  // 解决超大数字类型转换改变了的问题
  transformResponse: [
    function(data) {
      try {
        return JSONBig.parse(data)
      } catch (error) {
        return data
      }
    }
  ]
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error

    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log(response, 1)
    const status = response.status.toString()
    if (status.startsWith('2')) {
      return response.data
    }
    console.log(response, 'response-error')
  },
  error => {
    console.log('debug', error) // for debug
    error.response.data.message && message.error(error.response.data.message)
    return Promise.reject(error)
  }
)

export default service
